#include "maindialog.h"
#include "ui_maindialog.h"

MainDialog::MainDialog(QWidget *parent)
    : QDialog(parent)
    , ui(new Ui::MainDialog)
{
    ui->setupUi(this);
    server = new TcpServer(this, port);
    addLog(QString("server started at %1.").arg(port));
    connect(server, &TcpServer::serverStatusChange, this, &MainDialog::serverStatusChange);
    // connect(server, &TcpServer::doBroadCast, this, &MainDialog::broadcast, Qt::DirectConnection);
}

MainDialog::~MainDialog()
{
    server->close();
    delete ui;
}

void MainDialog::serverStatusChange(Message* msg)
{
    auto userName = msg->getBody();
    switch (msg->getCmdType()) {
    case CmdType::Logout:{
        addLog(QString("%1 %2").arg(userName, "logout"));
        break;
    }
    case CmdType::Login:{
        addLog(QString("%1 %2").arg(userName, "login"));
    }
    default:
        break;
    }

}

// void MainDialog::broadcast(Message *msg)
// {
//     server->broadcast(*msg);
// }

void MainDialog::addLog(QString msg)
{
    auto now = QDateTime::currentDateTime();
    auto snow = now.toString("yyyy.MM.dd hh:mm:ss");
    auto log = QString("%1 %2\n").arg(snow, msg);
    ui->txtLog->append(log);
}

